import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { AuthService, IJwtPayLoad } from 'src/modules/auth/auth/auth/auth.service';
import { AccountEntity } from 'src/modules/system/account/entities/account.entity';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private readonly authService: AuthService,
  ) {
  }

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const ctx = GqlExecutionContext.create(context);
    const token = ctx.getContext().req.headers.token;
    if (token) {
      try {
        const user: IJwtPayLoad = this.authService.verifyToken(token);
        // 数据库查询当前账号是否存在，方式jwt被人破解，传递过来的数据，但是账号表中不存在
        const account = await AccountEntity.findOne(user.id, { select: ['id', 'username'] });
        if (account) {
          // 将当前账号信息挂载到req上
          ctx.getContext().req.user = account;
          return true;
        } else {
          throw new UnauthorizedException('当前账号不存在');
        }
      } catch (e) {
        throw new UnauthorizedException('您传递的token错误');
      }
    } else {
      throw new UnauthorizedException('你无权方法该接口');
    }
  }
}
